package com.trainfinder.proxy;

import java.io.BufferedInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.ServerSocket;
import java.net.Socket;

class ServiceProviderImpl implements ServiceProvider {

	private final Socket remoteSocket;

	private final Socket localSocket;

	private BufferedInputStream localSocketInputStream;

	public ServiceProviderImpl(ServerSocket localSocketServer)
			throws ServerCreationException {

		try {
			localSocket = localSocketServer.accept();

			BufferedInputStream inputStream = null;
			try {
				inputStream = new BufferedInputStream(localSocket
						.getInputStream());
			} catch (IOException e) {
				throw new ServerCreationException(e);
			}

			this.localSocketInputStream = inputStream;

			remoteSocket = new RemoteSocketProvider(inputStream)
					.getRemoteSocket();

		} catch (IOException e1) {
			throw new ServerCreationException(e1);
		}
	}

	public Service getLocalService() {
		return new AbstractService() {

			public InputStream getInputStream() throws IOException {
				return localSocketInputStream;
			}

			public OutputStream getOutputStream() throws IOException {
				return localSocket.getOutputStream();
			}

		};

	}

	public Service getRemoteService() {
		return new AbstractService(){

			public InputStream getInputStream() throws IOException {
				return new BufferedInputStream(remoteSocket.getInputStream());
			}

			public OutputStream getOutputStream() throws IOException {
				return remoteSocket.getOutputStream();
			}

		};
	}

	protected void finalize() throws Throwable {
	    try {
	    	remoteSocket.close();
	    	localSocket.close();
	    } finally {
	        super.finalize();
	    }
	}
}
